﻿using System.Data.SqlTypes;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;

namespace SBSqlToolkit.TextFunctions
{
    /// <summary>
    /// Provides regular expressions functionality to SQL server.
    /// </summary>
    public class RegularExpressions
    {
        /// <summary>
        /// Indicates whether the regular expression finds a match in the input string, 
        /// using the regular expression specified in the pattern parameter and the 
        /// matching options supplied in the options parameter.
        /// </summary>
        /// <param name="input">The string to search for a match.</param>
        /// <param name="pattern">The regular expression pattern to match.</param>
        /// <returns><c>true</c> if the regular expression finds a match; otherwise, <c>false</c>.</returns>
        [SqlFunction(IsDeterministic = true, IsPrecise = true)]
        public static SqlBoolean IsMatch(SqlString input, SqlString pattern)
        {
            if (input.IsNull || pattern.IsNull)
            {
                return SqlBoolean.False;
            }

            return Regex.IsMatch(input.Value, pattern.Value, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// Within a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.
        /// </summary>
        /// <param name="input">The string to search for a match.</param>
        /// <param name="pattern">The regular expression pattern to match.</param>
        /// <param name="replacement">The replacement string.</param>
        /// <returns></returns>
        [SqlFunction(IsDeterministic = true, IsPrecise = true)]
        public static SqlString Replace(SqlString input, SqlString pattern, SqlString replacement)
        {
            if (input.IsNull || pattern.IsNull || replacement.IsNull)
            {
                return SqlString.Null;
            }

            string result = Regex.Replace(input.Value, pattern.Value, replacement.Value, RegexOptions.IgnoreCase);

            return new SqlString(result);
        }

    }
}
